home *** CD-ROM | disk | FTP | other *** search
/ Info-Mac 4 / Info_Mac IV CD-ROM (Pacific HiTech Inc.)(August 1994).iso / Text Processing / ArsMagna PPC / ars.c < prev    next >
Text File  |  1994-06-16  |  47KB  |  1,320 lines

  1. /*
  2.    Copyright (c) Michael S. Morton
  3.      1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993
  4.    All rights reserved.
  5.  
  6.    Permission is granted to anyone to use this software for any purpose on
  7.    any computer, and to alter it and redistribute it freely, subject
  8.    to the following restrictions:
  9.  
  10.    0. This software is provided "as is" and without any express or implied
  11.       warranties, including, without limitation, the implied warranties of
  12.       merchantability and fitness for a particular purpose.
  13.  
  14.    1. The author is not responsible for the consequences of the use of this
  15.       software, no matter how awful, even if they arise from flaws in it.
  16.  
  17.    2. The origin of this software must not be misrepresented, either by
  18.       explicit claim or by omission.  The credits must mention that this
  19.       software is based on the algorithm as described in the November 1987
  20.       issue of BYTE Magazine. The credits must appear in the About... dialog
  21.       and any documentation.
  22.  
  23.    3. Altered versions must be plainly marked as such, and must not be
  24.       misrepresented as being the original software.  The credits must appear
  25.       in the About... dialog and any documentation.
  26.  
  27.    4. This software may not be sold except as part of a substantially
  28.              different program.
  29.  
  30.      5. The Boston Museum of Science is expressly forbidden to use this program
  31.              for profit or to produce revenue.
  32.  
  33.    6. This notice may not be removed or altered.
  34. */
  35.  
  36. /*    [Set tabs to 2 characters.]
  37.  
  38.         This is the source for Ars Magna v1.1, a version with some improvements but
  39.         at least one serious bug.  It was never widely released.
  40.  
  41.         This source is not up-to-date, except for this comment.
  42.  
  43.         I plan to return to work on anagram engines and user interfaces someday, but
  44.         it's not going to be soon.  I've been thinking hard about user interfaces
  45.         for this app since 1984 (the original app was done in '82), and haven't come
  46.         up with anything good.  My hope is that various developers will experiment,
  47.         steal each other's best ideas, and in general have a real good time.  I've
  48.         already seen some people take Ars Magna's bad user interface and produce a
  49.         worse one; get creative here, folks, will ya?
  50.  
  51.         A few disconnected ideas, more or less off the top of my head:
  52.  
  53.             * I want to be able to say "Show me everything with word ____"
  54.             * Then, of course, the remaining mainstream anagrams omit that word
  55.             *    Similarly, I want to be able to say "Show me everything with words ____
  56.                 and ____".
  57.             * I want to be able to say "Don't ever show me this word during this session"
  58.             * I want to be able to say "Don't ever show me this word, ever"
  59.             * This version tries to do one-word anagrams, then two-word, etc.  It
  60.                 tends to lock up at the each length; there's some obvious pruning
  61.                 that can be done here.
  62.             *    Reviewing the output can take hours, so:
  63.                 (1) the user should be able to do nearly everything with the keyboard
  64.                 (2) they should be able to save their complete search state
  65.             * The app should handle various dictionary formats, and set one or more
  66.                 default dictionaries as a preference.
  67.             * I've never been able to find foreign-language dictionaries; anyone
  68.                 know if there are public-domain ones around?
  69.             *    Word order and search order are very important to producing good
  70.                 anagrams early in the search.  What are the possible orderings?
  71.                 Which help in which ways?  How should the user control them?
  72.             * The list of eligible words should be displayed somewhere.  The user
  73.                 should be able to save it, specify hot words to try first, etc.
  74.             *    There should be a way to show incomplete anagrams, with the user
  75.                 specifying the maximum number of unused letters to show (zero would
  76.                 make the app behave as it does now).  They should be able to rearrange
  77.                 unused letters under keyboard or mouse control.
  78.             *    Once you've found an anagram which looks interesting, the app should
  79.                 let you rearrange them under keyboard or mouse control, or quickly
  80.                 display all orderings of the words.  Of course, a quick command should
  81.                 save an anagram to the list of cool anagrams.
  82.             *    When listing anagrams, a change in a given column should be highlighted
  83.                 to wake up a bored user.  This version does this crudely with capitals
  84.                 when a word first appears in a column, as in this example:
  85.                         CLIMATE HO MR NO
  86.                         climate ho mr ON
  87.                         climate MR NO OH
  88.                         climate mr OH ON
  89.             *    I hate retyping anagrams for posting or publication, so the app should:
  90.                 (1) Allow easy word-shuffling and punctuation and capitalization
  91.                         changes in the saved list of cool anagrams.
  92.                 (2) Quickly check a text file or the clipboard's contents to make
  93.                         sure they're right.
  94.             *    You should be able to export the list of cool anagrams to the
  95.                 clipboard or a text file.
  96.             * The current bit-banging scheme makes sure that an anagram contains
  97.                 exactly the right number of letters, by adding them up and checking
  98.                 that the count is exactly right.  This could be generalized to make
  99.                 sure the count is in a certain range for an attribute OTHER than a
  100.                 letter.  This is useful for:
  101.                 (a) I'm using several dictionaries, but only one is new, so show me
  102.                         only anagrams with one or more words from that dictionary.
  103.                 (b)    I want to see no more than 2 one-letter words.
  104.                 (c)    I want to see at least one word that I've marked as interesting.
  105.             *    Or, if you want to use the counter scheme for "no more than one of"
  106.                 or "at least one of", you could use AND and OR instead of addition.
  107.             *    I should be able to quickly count all the anagrams which will result
  108.                 from a partial anagram I've found, to help me decide when to explore.
  109.             *    I've tried a NeXT-style browser interface and, at least the way I did
  110.                 it, it was lousy.  Not interactive enough.
  111.             *    You might be able to prune or order anagrams on the basis of available
  112.                 or constructed information on word-pair frequencies in natural languages.
  113.                 This idea strikes me as promising, but I haven't done anything with it.
  114.             *    Extra credit: Parse the anagrams as natural language to find good ones.
  115.  
  116.             Don't expect that doing all of the above will give you a good app.  This is
  117.             just a laundry list, not an overall vision of a good UI.  I've talked to
  118.             good anagrammers, and they work on paper and in their heads -- devising an
  119.             interface which is easier for them, not just for a beginner, will be hard.
  120.  
  121.         If you develop an app, prototype or not, commercial or not, I'd be interested
  122.         in seeing it and commenting on the UI.  If you feel like sharing the source,
  123.         I'd be interested in that, too.
  124.  
  125.         Keep in touch,
  126.                 Mr. Machine Tool
  127.                 February, 1993
  128.  
  129.         Email:    Mike_Morton@Proponent.com
  130.         Paper:    Mike Morton, POB 11299, Honolulu, HI  96828
  131. */
  132.  
  133. #include <stdio.h>
  134. #include <stdlib.h>
  135. #include <string.h>
  136. //#include <console.h>
  137.  
  138. #include "SIOUX.h"
  139. #include <Types.h>
  140. #include <Files.h>
  141.  
  142. /* Easily changeable constants: */
  143. #define STRMAX            100                                /* size of some strings */
  144. #define MAXFILES        10                                /* maximum number of dictionaries */
  145. #define MAXMASKS        10                                /* number of "masks" for bitbanging */
  146.                                                         /* note that doanagram() depends on MAXMASKS */
  147. #define DFTFILE            "anagram dict"                    /* default dictionary name */
  148. #define    WPTRDELTA        512                                /* # of word ptrs to add */
  149. #define TEXBSIZE        2048                            /* size of a block of text */
  150. #define DOTFREQ            25                                /* anagrams per dot, when filing/counting */
  151. #define DOTSPERLINE        40                                /* dots per line for filing/counting */
  152. #define PAGESIZE        22                                /* lines between prompts */
  153. #define WORDCHUNK        5000                            /* size of chunks for words */
  154.  
  155. /* Not-so-easily-changeable things: */
  156. #define mask        long                                    /* masks are stored in longwords */
  157. #define maskwidth    8*sizeof(mask)            /* and their size is important */
  158.  
  159. /* Global stuff -- phrase information: */
  160. char phrase [STRMAX];                                    /* the phrase to be anagrammed */
  161. char origphrase [STRMAX];                            /* unmunged copy of phrase */
  162. short freqs [26];                                            /* frequency table for phrase */
  163. short letmask [26], letbit [26];            /* mask, bit positions for each letter */
  164. short letwidth[26];                                        /* width in mask of each letter */
  165. short usedmasks;                                            /* count of used masks */
  166. short minWords, maxWords;
  167.  
  168. mask oflodesc [MAXMASKS];                            /* descriptor used to detect overflow */
  169. mask phrasedesc [MAXMASKS];                        /* descriptor for main phrase */
  170. mask startdesc [MAXMASKS];                        /* starting descriptor for search */
  171.  
  172. /* Global stuff -- Dictionary information */
  173. short numdicts = 0;                                        /* number of dictionaries */
  174. FILE *dicts [MAXFILES];                                /* dictionary files */
  175. short numwords;                                                /* number of eligible words */
  176. short maxwords = 0;                                        /* number of words which fit in *wordlist */
  177. char **wordlist = NULL;                                /* words[0..maxwords-1],
  178.                                                                                             with 0..numwords-1 used */
  179. mask *worddescs;                                            /* descriptors [0..numwords-1] */
  180. struct wchunk {
  181.     struct wchunk *next;
  182.     char text [WORDCHUNK];
  183. };
  184. char *nextwcp = NULL;                                    /* pointer to next char to fill */
  185. short nextwleft = 0;                                    /* chars left in this block */
  186. struct wchunk *curchunk = NULL;                /* pointer to current chunk */
  187. struct wchunk *chunkhead = NULL;            /* pointer to first chunk */
  188.  
  189. /* Global stuff -- For printing anagrams */
  190. char *anawords [20];                                    /* stacked words */
  191. char **anaptr;                                                /* pointer to first unused slot */
  192. FILE *anafile;                                                /* stdin for screen, output file, or NULL */
  193. short silent;                                                    /* 1 iff not printing to screen */
  194. unsigned long anacount;                                /* number of anagrams found */
  195. unsigned long startt, endt, tottime;    /* timing information */
  196. short paging;                                                    /* pause after each screenful? */
  197.  
  198. enum {                                                                /* types of help */
  199.     dict1, dict1dft, dict2,
  200.     anahelp,
  201.     scf,
  202.     overadd,
  203.     quithelp,
  204.     helppage, helppaused
  205. };
  206.  
  207. #define DR register                                        /* Debugging Register */
  208. #define pf printf
  209.  
  210. void dophrase (void);
  211. void clean (char *s);
  212. void cleannl (char *s);
  213. void makefreqs (char *s);
  214. short findbits (void);
  215. short findbitwidth (short count);
  216.  
  217. void makeof (void);
  218. short makedesc (char *str, mask desc[]);
  219. short okword (char *str);
  220. short getdicts (void);
  221. short getwords (void);
  222. short storeword (char *word);
  223. void freewords (void);
  224. short mycmp (char **s1p, char **s2p);
  225. void sortwords (void);
  226. void nodups (void);
  227. void printwords (void);
  228. void makeWrite (FILE *f);
  229. short makemasks (void);
  230. void freemasks (void);
  231. short doanagrams (short curword, mask *curstate, short wordsLeft);
  232. short printana (void);
  233. short exitcheck (void);
  234. void getoutput (void);
  235. short openoutfile (char *name);
  236. short getline (char *prompt, char *keywords, short keyneeded, char *dft, char *reprompt,
  237.                         short helpstate, char *response);
  238. void dohelp (short state);
  239. short keyfind (char *words, char *oneword);
  240. short findstr (char *master, char *sub);
  241. short strNequal (char *s1, char *s2, short size);
  242. long msec (void);
  243. void starttimer (void);
  244. void stoptimer (void);
  245. void inittimer (void);
  246. void printtime (void);
  247. void chkerr (short i);
  248.  
  249. void main (void)
  250. {
  251.  
  252.     SetSIOUXBufferMode(SIOUXFullBuffering);
  253.     //cgotoxy (0, 0, stdout);                        /* don't scroll initial stuff */
  254.     pf (" \n");
  255.     pf ("********************************************************************************\n");
  256.     pf ("*      A R S  M A G N A (TM), an anagram generator, version 1.1 (24 Sep '90)   *\n");
  257.     pf ("* Copyright 1986-1993 Michael Morton (aka 'Mr. Machine Tool', 'Harmonic motel')*\n");
  258.     pf ("*                            All rights reserved.                              *\n");
  259.     pf ("*    Based on my algorithm as described in the November 1987 issue of BYTE.    *\n");
  260.     pf ("*                                                                              *\n");
  261.     pf ("* Ported to Think C 5.0.4 by Matthew Xavier Mora              (9-21-93)        *\n");
  262.     pf ("*                            mxmora@unix.sri.com                               *\n");
  263.     pf ("* Ported to MWC DR3       by Matthew Xavier Mora              (6-06-94)        *\n");
  264.     pf ("*                            mxmora@unix.sri.com                               *\n");
  265.     pf ("********************************************************************************\n");
  266.     pf ("\n");
  267.     pf ("QUICK...This program finds anagrams for a phrase or name.  You can just press\n");
  268.     pf (" INFO   RETURN for most questions, or type 'HELP' at any point for more info.\n");
  269.     pf ("\n");
  270.  
  271.     numdicts = getdicts ();                            /* just once: open up dictionaries */
  272.  
  273.     while (1)
  274.     {
  275.         printf ("\n");
  276.         getline ("What's the phrase you'd like to anagram? ",
  277.                             "", 0, "", "\nWhat's the phrase you'd like to anagram? ",
  278.                             anahelp, phrase);
  279.         strcpy (origphrase, phrase);            /* remember it, before we... */
  280.         clean (phrase);                                        /* clean up the string */
  281.  
  282.         if (strlen (phrase) == 0)                            /* nothing there? */
  283.             printf ("Come on, don't be shy...  try something!\n");
  284.         else dophrase ();
  285.  
  286.         if ((anafile != NULL) && (anafile != stdout))
  287.             fclose (anafile);                                /* heavy-handed to put this here... */
  288.     }                                                        /* end of infinite main loop */
  289. }                                                            /* end of main program */
  290.  
  291. void dophrase ()
  292. {
  293.     short i;                                                        /* counter for masks */
  294.     char response [STRMAX];                            /* dummy input buffer */
  295.     short wordCount;
  296.     short keynum;
  297.  
  298.     makefreqs (phrase);                                    /* build the frequency table */
  299.  
  300.     if (findbits () == 0)                                /* choose bit fields; check size */
  301.     {
  302.         printf ("Sorry -- that phrase is too long to handle.\n");
  303.         return;
  304.     }
  305.  
  306.     getoutput();                                                /* where should we put this stuff? */
  307.  
  308.     if (anafile == stdout)
  309.         paging = getline ("Want output to pause after each page [RETURN for YES]? ",
  310.                                             "#no#yes", 1, "yes",
  311.                                             "Please type YES or NO.  Want output to pause after each page? ",
  312.                                             helppage, response);
  313.     else paging = 0;                                        /* no paging if not printing */
  314.  
  315.     makeof ();                                                    /* compute overflow and "full" descriptors */
  316.  
  317.     makedesc (phrase, phrasedesc);            /* make descriptor for phrase; ignore result (can't fail) */
  318.  
  319.     for (i = 0; i <= usedmasks; i++)        /* loop through all masks we used... */
  320.         startdesc[i] =                                        /* and for each one, the starting descriptor... */
  321.             phrasedesc[i];                                    /* ...is the full one */
  322.  
  323.     getwords ();                                                /* read in words for this phrase */
  324.     if (numwords == 0) return;                    /* bag it?  OK */
  325.     sortwords ();                                                /* get 'em in the right order */
  326.     nodups ();                                                    /* eliminate duplicate words */
  327.     printwords ();                                            /* dump 'em to a file */
  328.     if (makemasks () == 0) {
  329.         printf ("Sorry!  Couldn't make Masks.");
  330.         return;            /* make masks for them all -- return on error */
  331.     }
  332.  
  333.     inittimer ();
  334.  
  335.     if (anafile != NULL)
  336.         chkerr (fprintf (anafile, "\n\n*** anagrams for '%s' ***\n\n", origphrase));
  337.     for (wordCount = 1; wordCount < 100; wordCount++)
  338.     {
  339.         anaptr = anawords;                                /* point to base of stack */
  340.         anacount = 0;                                            /* no anagrams found so far */
  341.         doanagrams (0, startdesc, wordCount); /* print (or whatever) all anagrams */
  342.         if (anafile != stdout) printf ("\n");    /* don't print after dots */
  343.         printf ("Anagrams found with %d words: %ld.\n", wordCount, anacount);
  344.         stoptimer ();
  345.         keynum = getline ("   ...more (next size of anagram)... ",
  346.             "#stop", 0, "", "   ...more (next size of anagram)... ",
  347.             helppaused, response);
  348.         starttimer ();
  349.         if (keynum == 0)                                /* bag this anagram? */
  350.             wordCount = 100;                            /* break the loop */
  351.     }
  352.  
  353.     printtime ();
  354.  
  355.     freemasks ();                                                /* ditch the masks */
  356.     freewords ();                                                /* ditch the words */
  357. }                                                                            /* end of dophrase() */
  358.  
  359. /* clean -- Clean up a string in place: map all letters to lowercase and
  360.    discard everything else. */
  361.  
  362. void clean (s)
  363.     DR char *s;                                                    /* UPDATE: string to clean */
  364. {
  365.     DR char *in = s, *out = s;                    /* reading, writing pointers */
  366.     DR char c;                                                    /* working copy of character */
  367.  
  368.     while (c = *in++)                                        /* loop through whole input string */
  369.     {
  370.         if ( (c>='A') && (c<='Z') )                /* uppercase alphabetic? */
  371.             c -= ('A' - 'a');                                /* yup: map it to lower */
  372.         if ( (c>='a') && (c<='z') )                /* after mapping, is it lower case? */
  373.             *out++ = c;                                            /* yup: store it */
  374.     }                                                                        /* end of loop mapping&discarding */
  375.     *out++ = c;                                                    /* store the final null */
  376. }                                                                            /* end of clean() */
  377.  
  378. /* cleannl -- Toss all newlines out of a string, in place. */
  379.  
  380. void cleannl (s)
  381.     register char *s;
  382. {
  383.     register char *in = s;
  384.     register char *out = s;
  385.     register char c;
  386.  
  387.     while (c = *in++)
  388.         if (c != '\n')
  389.             *out++ = c;
  390.     *out++ = '\0';
  391. }
  392.  
  393. /* makefreqs -- Take a phrase and produce a frequency table from it.  The
  394.    phrase has already been cleaned up, so we know it contains only the
  395.    characters 'a'..'z'. */
  396.  
  397. void makefreqs (s)
  398.     DR char *s;                                                    /* INPUT: string to analyze */
  399.     /* GLOBAL OUTPUT: frequency table */
  400. {
  401.     DR short i;                                                    /* traditional loop index */
  402.  
  403.     for (i = 0; i<26; i++)                            /* loop through and initialize... */
  404.         freqs [i] = 0;                                        /* ...the frequency array */
  405.  
  406.     while (*s)                                                    /* while there's more to the string... */
  407.     {
  408.         freqs [*s - 'a'] ++;                            /* incremement slot for this letter */
  409.         s++;                                                            /* and skip to the next character */
  410.     }                                                                        /* end of loop through string */
  411.  
  412. }                                                                            /* end of makefreqs() */
  413.  
  414.  
  415. /* findbits -- Given the frequency table, find the bit position for each
  416.    character found in the original phrase.  Nonexistent letters are
  417.    ignored.  We may run out of room in the masks in doing this; we
  418.    return 0 on failure. */
  419.  
  420. short findbits ()                                            /* zero <=> failure */
  421.     /* GLOBAL INPUT: frequency table */
  422.     /* GLOBAL OUTPUT: whichword[], whichbit[], count of used masks */
  423. {
  424.     short letter;                                                /* letter value (0..25) */
  425.     short curword = 0, curbit = 0;            /* initial bit and word */
  426.     short width;                                                /* bitwidth of letter's field */
  427.  
  428.     for (letter = 0; letter < 26; letter++)    /* loop through all letters */
  429.     {
  430.         if (freqs[letter] != 0)                        /* any occurrences of this letter? */
  431.         {                                                                    /* yes: find where it'll go */
  432.             width = findbitwidth (freqs [letter]); /* how much room does it need? */
  433.             if (curbit+width > maskwidth)     /* too wide for this word? */
  434.             {                                                                /* yes: have to kick into next word */
  435.                 curword++; curbit = 0;                /* go to start of next word */
  436.                 if (curword >= MAXMASKS)             /* no more room? */
  437.                     return (0);                                    /* no more: report failure */
  438.             }                                                                /* end of kicking into next word */
  439.  
  440.             letmask [letter] = curword;            /* remember which word we go in */
  441.             letbit [letter] = curbit;                /* and bit position in the word */
  442.             letwidth [letter] = width;            /* and the width */
  443.             curbit += width;                                /* advance past this bit field */
  444.         }                                                                    /* end of handling letter found in phrase */
  445.     }                                                                        /* end of loop through A..Z */
  446.  
  447.     usedmasks = curword;                                /* remember highest used mask */
  448.     return (1);                                                    /* indicate success */
  449. }                                                                            /* end of findbits() */
  450.  
  451. /* findbitwidth -- Find the number of bits needed to store a single letter
  452.    up to the specified frequency.  Our output looks like this:
  453.            Frequency:        Width (+ one overflow bit)
  454.            0                <undefined>
  455.            1                1 (+ 1)
  456.            2..3            2 (+ 1)
  457.            4..7            3 (+ 1)
  458.    ...etc. */
  459.  
  460. short findbitwidth (DR short count)                        /* find width of field to hold "count" */
  461.                                                 /* INPUT: frequency of letter */
  462. {
  463.     DR short width = 0;                                    /* result */
  464.  
  465.     while (count != 0)                                    /* loop 'til all bits discarded */
  466.     {
  467.         width++;                                                    /* counting the bits... */
  468.         count >>= 1;                                            /* ...and chucking out one more */
  469.     }                                                                        /* end of loop counting bits */
  470.  
  471.     width ++;                                                        /* and one more for the overflow */
  472.     return (width);                                            /* that's the answer */
  473. }                                                                            /* end of findbitwidth() */
  474.  
  475.  
  476. /* makeof -- Find the descriptors for the "overflow" and "full" descriptors.
  477.    The former has the bit just ABOVE each bit field set.  ANDing with this
  478.    set of masks will detect when the thing overflows.  The latter is the
  479.    former minus one in each bit field -- an almost full field. */
  480.  
  481. void makeof ()
  482.     /* GLOBAL INPUT: frequency table, letter information, count of masks */
  483.     /* GLOBAL OUTPUT: oflodesc */
  484. {
  485.     short l;                                                        /* letter number */
  486.     short mnum, bnum, bwidth;                        /* mask #, bit #, field width */
  487.     mask onebit, ovbit;                                    /* bits for single letter, overflow */
  488.     short i;                                                        /* usual counter */
  489.  
  490.     for (i = 0; i <= usedmasks; i++)        /* clean out... */
  491.         oflodesc [i] = 0;                                    /* ...each overflow mask */
  492.  
  493.  
  494.     for (l = 0; l < 26; l++)                        /* loop through letters */
  495.         if (freqs [l] != 0)                                /* any letters in the phrase */
  496.         {
  497.             bnum = letbit [l];                            /* what's the bit # for this letter? */
  498.             bwidth = letwidth [l];                    /* how wide is the field? */
  499.             mnum = letmask [l];                            /* and which mask does field go in? */
  500.  
  501.             onebit = 1;                                            /* start with a right-aligned 1 */
  502.             onebit <<= bnum;                                /* ...align it with the field */
  503.             ovbit = onebit << (bwidth-1);        /* and find where the overflow bit is */
  504.  
  505.             oflodesc [mnum] |= ovbit;                /* put the overflow bit in */
  506.         }                                                                    /* end of handling letter in phrase */
  507. }                                                                            /* end of makeof() */
  508.  
  509.  
  510.  
  511. /* makedesc -- Create the descriptor for a string.  If the string contains
  512.    too many of any letter, we return zero to say so. */
  513.  
  514. short makedesc (str, desc)                        /* returns zero <=> failure */
  515.     register char *str;                                    /* INPUT: string to analyze */
  516.     register mask desc[];                                /* OUTPUT: descriptor for string */
  517.     /* GLOBAL INPUT: frequency table, letter information */
  518. {
  519.     register short l;                                        /* letter number */
  520.     register char c;                                        /* character from the string */
  521.     short sfreqs [26];                                    /* string's frequency profile */
  522.     register short i;                                        /* loop counter */
  523.     register mask b;                                        /* a bit, for ORing into the desc */
  524.  
  525.     if (*str == '\0')                                        /* null string? */
  526.         return (0);                                                /* no good */
  527.  
  528.     for (i = 0; i <= usedmasks; i++)        /* go through all used masks... */
  529.         desc[i] = 0;                                            /* ...initializing their descriptors */
  530.  
  531.     for (l = 0; l < 26; l++)                        /* loop through all letters... */
  532.         sfreqs [l] = 0;                                        /* zeroing their frequency */
  533.  
  534.     while (c = *str++)                                    /* pick up all characters in str... */
  535.         sfreqs [c - 'a'] ++;                            /* ...tallying up their count */
  536.  
  537.     for (l = 0; l < 26; l++)                        /* loop through all letters... */
  538.         if (sfreqs [l] != 0)                            /* did it occur in the string? */
  539.         {
  540.             if (sfreqs [l] > freqs[l])            /* did it occur more than in the phrase? */
  541.                 return (0);                                        /* yes: fail */
  542.             b = sfreqs [l];                                    /* start with the count */
  543.             b <<= letbit [l];                                /* shift it into the field */
  544.             desc [letmask [l]] +=    b;                /* now add it into the mask */
  545.         }                                                                    /* end of handling letter in str */
  546.  
  547.     return (1);                                                    /* we're OK -- say so */
  548. }                                                                            /* end of makedesc */
  549.  
  550. /* okword -- See if a string is eligible for use in anagrams.
  551.    We return zero if not. */
  552.  
  553. short okword (str)                                        /* returns zero <=> failure */
  554.     register char *str;                                    /* INPUT: string to analyze */
  555.     /* GLOBAL INPUT: frequency table */
  556. {
  557.     register short l;                                        /* letter number */
  558.     register char c;                                        /* character from the string */
  559.     short sfreqs [26];                                    /* string's frequency profile */
  560.  
  561.     if (*str == '\0')                                        /* null string? */
  562.         return (0);                                                /* no good */
  563.  
  564.     for (l = 0; l < 26; l++)                        /* loop through all letters... */
  565.         sfreqs [l] = 0;                                        /* zeroing their frequency */
  566.  
  567.     while (c = *str++)                                    /* pick up all characters in str... */
  568.     {
  569.         c -= 'a';
  570.         if (++sfreqs [c] > freqs[c])            /* ...tallying up their count */
  571.             return (0);                                            /* ...and checking each one */
  572.     }
  573.     
  574.     return (1);                                                    /* we're OK -- say so */
  575. }                                                                            /* end of okword */
  576.  
  577. /* getdicts -- Get and open up at least one dictionary. */
  578.  
  579. short getdicts ()                                            /* return count of opened dicts */
  580.     /* GLOBAL OUTPUT: dicts[] */
  581. {
  582.     short count = 0;                                        /* initially none found */
  583.     short done = 0;                                            /* done flag */
  584.     short defaultavail;                                    /* default-file-failed flag */
  585.     char dictname [STRMAX];                            /* dictionary file name */
  586.     FILE *testfile;                                            /* used for checking for default file */
  587.     short helptype;
  588.  
  589.     /* is the default file available? */
  590.  
  591.     testfile = fopen (DFTFILE, "r");
  592.     if (testfile == NULL)                                /* blew it? */
  593.         defaultavail = FALSE;                            /* yup -- remember it's not there */
  594.     else {                                                            /* found it */
  595.         defaultavail = TRUE;                            /* remember this */
  596.         fclose (testfile);                                /* and chuck it */
  597.     }                                                                        /* end of successful find */
  598.  
  599.     while (! done)                                            /* loop 'til we're happy */
  600.     {
  601.         if (count == 0)                                        /* no files open yet? */
  602.         {                                                                    /* yes: special greeting */
  603.             printf ("Name of dictionary file");
  604.             helptype = dict1;                                /* set help state */
  605.             if (defaultavail)
  606.             {
  607.                 printf (" [press RETURN to use '%s']", DFTFILE);
  608.                 helptype = dict1dft;
  609.             }
  610.         }
  611.         else
  612.         {
  613.             printf ("Next dictionary name [press RETURN if no more]");
  614.             helptype = dict2;
  615.         }
  616.         getline ("? ", "", 0, "", "Dictionary name? ", helptype, dictname); /* ask 'em */
  617.  
  618.         if (strlen (dictname) == 0)                /* just RETURN? */
  619.         {                                                                    /* handle untalkative input */
  620.             if (count == 0)                                    /* no files yet? */
  621.             {
  622.                 if (defaultavail == 0)                /* no files yet? */
  623.                     printf ("Come now, don't be shy.\n");    /* no default available */
  624.                 else strcpy (dictname, DFTFILE);    /* use default name */
  625.             }
  626.             else done = TRUE;                                /* one or more files is OK */
  627.         }                                                                    /* end of handling RETURN */
  628.  
  629.         if (strlen (dictname) != 0)                /* did we read (or plug in) a name? */
  630.         {                                                                    /* we got a name... */
  631.             testfile = fopen (dictname, "r"); /* ...try to open it */
  632.             if (testfile == NULL)                        /* failed? */
  633.             printf ("Sorry, can't find the file '%s'.  Try again?\n", dictname);
  634.             else dicts [count++] = testfile;    /* stack this dict; bump count */
  635.         }                                                                    /* end of processing input name */
  636.  
  637.         if (count >= MAXFILES)                        /* full up? */
  638.         {                                                                    /* yes: force an exit */
  639.             printf ("\nThat's enough files -- can't handle any more!\n");
  640.             done = TRUE;
  641.         }
  642.  
  643.     }                                                                        /* end of looping 'til done */
  644.  
  645.     return (count);                                            /* say how many dictionaries we got */
  646. }                                                                            /* end of getdicts() */
  647.  
  648. /* getwords -- Read in all the usable words from all the dictionaries.
  649.    We set the count of usable words, including zero if there are
  650.    none.  If we run out of memory, we return zero.  Either way, we
  651.    print a message so the caller doesn't have to. */
  652.  
  653. short getwords ()                                                        /* we return the count of words */
  654. {
  655.     register short dnum;                                /* dictionary number */
  656.     register FILE *infile;                            /* one dictionary's FILE */
  657.     char word [STRMAX];                                    /* one word from the dictionary */
  658.     char cleanword [STRMAX];                        /* cleaned-up copy */
  659.     register long readcount = 0;                /* count of words read */
  660.     char lastline [STRMAX];                            /* last line read */
  661.     char inpline [STRMAX];                            /* raw input line */
  662.     char *inp;                                                    /* input line pointer */
  663.     short common;                                                /* count of letters in common */
  664.  
  665.     numwords = 0;                                                /* no words yet */
  666.     for (dnum = 0; dnum < numdicts; dnum++)    /* loop through all dictionaries */
  667.     {
  668.         printf ("Reading dictionary...");
  669.         infile = dicts [dnum];                        /* grab this dictionary */
  670.         fseek (infile, 0L, 0);                        /* reset to start of file */
  671.         while (1)                                                    /* EOF is noticed in mid-loop */
  672.         {
  673.             if (fgets (inpline, STRMAX, infile) == NULL)    /* get a word */
  674.                 break;                                                /* if end-of-file, quit */
  675.             common = 0;
  676.             inp = inpline;                                    /* point to start of input line */
  677.             while ( (*inp >= '0') && (*inp <= '9') ) /* process digits... */
  678.                 common = (common * 10) + (*inp++ - '0'); /* ...accumulate number */
  679.             lastline [common] = '\0';                /* take first N chars of last line */
  680.             strcat (lastline, inp);                    /* and add the rest */
  681.  
  682.             strcpy (word, lastline);                /* now get the word */
  683.             cleannl (word);                                    /* ditch the newline */
  684.             strcpy (cleanword, word);                /* make a copy... */
  685.             clean (cleanword);                            /* ...and clean it up */
  686.             readcount++;
  687.             if ((readcount % 1000) == 0)
  688.             {    printf (".");
  689.                 fflush (stdout);                            /* don't let this line buffer up */
  690.             }
  691.  
  692.             if (okword (cleanword) != 0)        /* can it be used in anagrams? */
  693.             {                                                                /* yes! */
  694.                 if (storeword (word) == 0)        /* store it; check for failure */
  695.                     return (0);                                    /* say we can't do it */
  696.             }                                                                /* end of handling useful word */
  697.         }                                                                    /* end of loop through one dict */
  698.         printf ("\n");                                        /* ... left us in mid-line */
  699.     }                                                                        /* end of loop through dictionaries */
  700.  
  701.     if (numwords == 0)                                    /* NOTHING found? */
  702.         printf ("Sorry -- absolutely NO usable words found!\n");
  703.     else printf ("%d usable words found.\n", numwords);
  704.  
  705. }                                                                            /* end of getwords () */
  706.  
  707. short storeword (word)
  708.     register char *word;
  709. {
  710.     register char *memword;                            /* allocated word */
  711.     register short len = 1 + strlen (word);    /* size we need to store word */
  712.     register short newmaxwords;                    /* new array size */
  713.     register short size;                                /* size of new block */
  714.  
  715.     if (len > nextwleft)                                /* no room in this chunk? */
  716.     {
  717.         struct wchunk *newchunk;
  718.  
  719.         newchunk = (struct wchunk *) malloc (sizeof (struct wchunk));
  720.         if (newchunk == NULL)                            /* blew it? */
  721.         {
  722.             printf ("Sorry -- not enough memory for this anagram!\n");
  723.             freewords ();                                        /* discard accumulated words */
  724.             return (0);                                            /* say so */
  725.         }
  726.         newchunk -> next = chunkhead;            /* make this... */
  727.         chunkhead = newchunk;                            /* ...the head chunk */
  728.         curchunk = newchunk;                            /* which (coincidentally) is the current one, too */
  729.         nextwcp = newchunk -> text;                /* point to first usable character */
  730.         nextwleft = WORDCHUNK;                        /* remember available size */
  731.     }
  732.  
  733.     memword = nextwcp;                                    /* point to first free character */
  734.     nextwcp += len;                                            /* skip to next slot */
  735.     nextwleft -= len;                                        /* and debit available stuff */
  736.  
  737.     strcpy (memword, word);                            /* store the word in new chunk */
  738.  
  739.     if ((numwords+1) >= maxwords)                /* will this overflow the current list? */
  740.     {
  741.         newmaxwords = maxwords + WPTRDELTA;    /* jump to next size */
  742.         size = newmaxwords * sizeof (char *); /* find new size */
  743.  
  744.         if (wordlist == NULL)
  745.             wordlist = (char **) malloc (size); /* first time */
  746.         else wordlist = (char **) realloc (wordlist, size); /* grow the block */
  747.  
  748.         if (wordlist == NULL)                            /* blew it? */
  749.         {                                                                    /* looks that way */
  750.             printf ("Sorry -- not enough memory for this anagram!\n");
  751.             free (memword);                                    /* chuck word not yet in list */
  752.             freewords ();                                        /* discard accumulated words */
  753.             return (0);                                            /* say to give up */
  754.         }
  755.  
  756.         maxwords = newmaxwords;                        /* remember new maximum */
  757.     }                                                                        /* end of handling list overflow */
  758.  
  759.     wordlist [numwords++] = memword;        /* stack this word in the list */
  760.  
  761.     return (1);                                                    /* the sweet smell of success */
  762. }
  763.  
  764. void freewords ()
  765. {
  766.     struct wchunk *p;
  767.  
  768.     for (p = chunkhead; p = p -> next; p != NULL)
  769.         free (p);
  770.  
  771.     nextwcp = NULL;
  772.     nextwleft = 0;                                            /* force allocation next time */
  773.     curchunk = NULL;
  774.     chunkhead = NULL;
  775. }                                                                            /* end of freewords() */
  776.  
  777.  
  778. short mycmp (s1p, s2p)
  779.     char **s1p, **s2p;
  780. {
  781.     register char *s1 = *s1p;
  782.     register char *s2 = *s2p;
  783.     register short i;
  784.  
  785.     i = strlen (s2) - strlen (s1);    /* if S2 is longer, S1 is greater */
  786.  
  787.     if (i != 0)
  788.         return (i);
  789.     return (strcmp (s1, s2));
  790. }
  791.  
  792. void sortwords ()
  793. {
  794.     printf ("Sorting words..."); inittimer ();
  795.     qsort ((char *) wordlist, numwords, 4, (void *)mycmp);
  796.     printf ("\n");
  797. }
  798.  
  799. void nodups ()
  800. {
  801.     register short wordnum = 0;
  802.     register short move;
  803.  
  804.     while (wordnum < numwords-1)
  805.     {
  806.         if (strcmp (wordlist [wordnum], wordlist [wordnum+1]) != 0 )
  807.             wordnum ++;                                        /* different: go to next word */
  808.         else {                                                    /* same: have to move down */
  809.  
  810.             for (move = wordnum; move < numwords - 1; move++)
  811.                 wordlist [move] = wordlist [move+1];
  812.             -- numwords;
  813.         }
  814.     }
  815. }
  816.  
  817. void printwords ()
  818. {    char response [STRMAX];
  819.     FILE *f;
  820.     register short wordnum = 0;
  821.  
  822.     printf ("What file do you want the word list in [RETURN if none]? ");
  823.     gets (response);                                    /* get a line of input */
  824.     if (strlen (response) == 0)                /* pressed RETURN? */
  825.         return;                                                    /* yes: bag it */
  826.  
  827.     f = fopen (response, "a");                /* open, append */
  828.     if (f == NULL)
  829.     {    printf ("Can't output to that file; sorry!");
  830.         return;
  831.     }
  832.  
  833.     fseek (f, 0L, 2);                                    /* reset to the end */
  834.     while (wordnum < numwords)
  835.     {    fprintf (f, "%s\r", wordlist [wordnum]);
  836.         ++wordnum;
  837.     }
  838.  
  839.     /* makeWrite (f); */                                        /* make it MacWrite-able */
  840.     fclose (f);
  841. }
  842.  
  843. void makeWrite (f)
  844.     FILE *f;
  845. {    short refnum;
  846.     FInfo info;
  847.     Str255 s;
  848.  
  849.     //refnum = f->refnum;
  850.     GetFInfo ((StringPtr)&s, refnum, &info);
  851.     info.fdType = 'TEXT';
  852.     info.fdCreator = 'MACA';
  853.     SetFInfo ((StringPtr)&s, refnum, &info);
  854. }
  855.  
  856. short makemasks ()
  857.     /* GLOBAL INPUT: numwords, wordlist */
  858.     /* GLOBAL OUTPUT: worddescs[] */
  859. {
  860.     short i;
  861.     short onesize;
  862.     mask *descp;
  863.     char wordcopy [STRMAX];
  864.     long size;
  865.     
  866.     onesize = (usedmasks+1) * sizeof (mask);
  867.     size = (long) numwords * onesize;                    /* compute size of all descriptors */
  868.  
  869.     worddescs = (mask *) malloc (size);    /* find space for it */
  870.     if (worddescs == NULL)    {                        /* blew it? */
  871.         printf("Can't Alocate %ld bytes.",size);
  872.         return (0);
  873.     }
  874.     descp = worddescs;                                    /* point to the first descriptor slot */
  875.     for (i = 0; i < numwords; i++)            /* loop through every word... */
  876.     {
  877.         strcpy (wordcopy, wordlist [i]);    /* ...copy the word */
  878.         clean (wordcopy);                                    /* ...clean it up */
  879.         makedesc (wordcopy, descp);                /* ...and store each one's descriptor */
  880.         descp += (usedmasks+1);                        /* ...and bump to next slot */
  881.     }
  882.     return (1);                                                    /* no memory problems */
  883. }                                                                            /* end of makemasks() */
  884.  
  885. void freemasks ()
  886. {
  887.     free (worddescs);
  888. }
  889.  
  890. short doanagrams (register short curword,
  891.                  register mask *curstate,
  892.                  short wordCount)                    /* return 0 to halt search */
  893.                                                     /* current word number */
  894.                                                     /* descriptor for current state */
  895.                                                     /* words left to stack before we print anagram */
  896. {
  897.     mask newdesc [MAXMASKS];                        /* new descriptor */
  898.     register mask newmask;                            /* one mask from descriptor */
  899.     register mask *curdesc;                            /* current word's descriptor */
  900.     register long overflow;                            /* does this combination overflow? */
  901.     register long bitsleft;                            /* is this combination full? */
  902.  
  903.     curdesc = &worddescs [curword * (usedmasks+1)];
  904.  
  905.     wordCount--;                                                /* count the word we're going to stack */
  906.     while (curword < numwords)                    /* loop through all words after this one */
  907.     {
  908.  
  909. #define CASE(MNUM)                                                                                                                    \
  910.         newmask = curstate [MNUM] - curdesc [MNUM];    /* subtract from anagram */    \
  911.         if (overflow =                                        /* remember if there was oflo... */        \
  912.             (newmask & oflodesc [MNUM]))        /* and, if so, bag it */                            \
  913.                 break;                                                 /* note it; break out */                            \
  914.         newdesc [MNUM] = newmask;                    /* it's OK; store it */                                \
  915.         bitsleft |= newmask;                            /* note if done */
  916.  
  917.         bitsleft = 0;                                            /* assume complete 'til we see otherwise */
  918.         overflow = 0;                                            /* no overflow 'til we've seen it */
  919.         switch (usedmasks)
  920.         {
  921.             case 5:    CASE(5)
  922.             case 4:    CASE(4)
  923.             case 3:    CASE(3)
  924.             case 2:    CASE(2)
  925.             case 1:    CASE(1)
  926.             case 0:    CASE(0)
  927.         }
  928.  
  929.         if (! overflow)
  930.         {
  931.             *anaptr++ = wordlist [curword]; /* save this word */
  932.  
  933.             if ((! bitsleft)                                /* no bits left? */
  934.                     && (wordCount == 0))                /* ...and time to print? */
  935.             {
  936.                 if (printana () == 0)                    /* print it; do they want us to stop? */
  937.                   return (0);                                    /* yes: stop */
  938.             }
  939.             else if (wordCount)                            /* dive deeper only if caller wants more words */
  940.             {
  941.                 if (doanagrams (curword, newdesc, wordCount) == 0)
  942.                     return (0);
  943.             }
  944.  
  945.             --anaptr;                                                /* discard the word from the stack */
  946.         }
  947.  
  948.         curword++;                                                /* next word number */
  949.         curdesc += (usedmasks+1);                    /* next word's mask */
  950.     }
  951.  
  952.   return (1);                                                    /* continue the search */
  953. }                                                                            /* end of doanagrams() */
  954.  
  955. static char *lastanawords [20];
  956.  
  957. short printana ()                                            /* return 0 to stop current anagram */
  958. {
  959.     register char **p;
  960.     char response [STRMAX];                            /* dummy buffer for answer */
  961.     short keynum;                                                /* keyword number from getline() */
  962.     Boolean caps;
  963.  
  964.     ++anacount;                                                    /* that's one more anagram */
  965.  
  966.     if (anafile != stdout)                            /* not printing to screen? */
  967.     {
  968.         if ((anacount % DOTFREQ) == 0)        /* every once in a while... */
  969.         {
  970.             printf (".");                                        /* remind them we're here */
  971.             if (exitcheck () == 0)                    /* time to stop THIS anagram? */
  972.                 return (0);                                        /* yes */
  973.             if ((anacount % (DOTFREQ * DOTSPERLINE)) == 0)
  974.             {
  975.                 printf ("anagram #%ld: ", anacount);
  976.                 for (p = anawords; p < anaptr; p++)
  977.                     printf ("%s ", *p);
  978.                 printf ("\n");
  979.             }
  980.         }
  981.     }
  982.  
  983.     if (anafile == NULL) return (1);        /* no file?  no more to do here */
  984.  
  985.     if (! paging)                                                /* no way to stop? */
  986.     {
  987.         if (exitcheck () == 0)                        /* time to stop THIS anagram? */
  988.                 return (0);                                        /* yes */
  989.     }
  990.     else {
  991.         if ((anacount % PAGESIZE) == 0)
  992.         {
  993.             stoptimer ();
  994.             keynum = getline ("   ...more... ",
  995.                 "#stop", 0, "", "   ...more... ",
  996.                 helppaused, response);
  997.             starttimer ();
  998.             if (keynum == 0)                                /* bag this anagram? */
  999.                 return (0);                                        /* yup */
  1000.         }
  1001.     }
  1002.  
  1003.     /* Print the damned anagram already: */
  1004.     caps = false;
  1005.     for (p = anawords; p < anaptr; p++)
  1006.     {    if (lastanawords [p-anawords] != *p)    /* different word than showed up last time? */
  1007.             caps = true;
  1008.         if (caps)
  1009.         {    char buf [100];
  1010.             register char *bp;
  1011.             strcpy (buf, *p);
  1012.             bp = buf;
  1013.             while (*bp)
  1014.             {    if ((*bp >= 'a') && (*bp <= 'z'))
  1015.                     *bp += ('A'-'a');
  1016.                 bp++;
  1017.             }
  1018.             chkerr (fprintf (anafile, "%s ", buf));
  1019.         }
  1020.         else chkerr (fprintf (anafile, "%s ", *p));
  1021.         lastanawords [p-anawords] = *p;
  1022.     }
  1023.     chkerr (fprintf (anafile, "\n"));
  1024.  
  1025.     return (1);
  1026. }
  1027.  
  1028. short exitcheck ()                                        /* return 0 to stop this anagram */
  1029. {
  1030.     short c;
  1031.     short stopped = 0;
  1032.     short keynum;
  1033.     char str [STRMAX];
  1034.  
  1035. #if 0
  1036.     while (kbhit ())
  1037.         if (getchar () == ' ')
  1038.             stopped = 1;
  1039. #endif
  1040.  
  1041.     if (! stopped) return (1);                    /* continue */
  1042.  
  1043.     stoptimer ();
  1044.     keynum = getline (
  1045.         "\nType STOP for the next anagram, QUIT to leave the program,\nor anything else to continue? ",
  1046.         "#stop", 0, "", 
  1047.         "Type STOP for the next anagram, QUIT to leave the program,\nor anything else to continue? ",
  1048.         quithelp, str);
  1049.  
  1050.     starttimer ();
  1051.     if (keynum == 0)                                        /* typed STOP? */
  1052.         return (0);                                                /* yes: stop */
  1053.     else return (1);                                        /* no: continue */
  1054. }
  1055.  
  1056. void getoutput ()
  1057.     /* GLOBAL OUTPUT: anafile, silent */
  1058. {
  1059.     char response [STRMAX];
  1060.     short done = 0;
  1061.     short keywd;
  1062.  
  1063.     printf ("Print to the screen, print to a file, or just count anagrams?\n");
  1064.     while (! done)
  1065.     {
  1066.         keywd = getline ("Type COUNT or a filename [or press RETURN for SCREEN]? ",
  1067.                         "#screen#count", 0, "screen",
  1068.                         "Type COUNT or a filename [or press RETURN for SCREEN]? ",
  1069.                         scf, response);
  1070.  
  1071.         if (keywd == 0)
  1072.         {                                                                    /* handle SCREEN */
  1073.             anafile = stdout;                                /* output to screen */
  1074.             done = TRUE;
  1075.         }
  1076.         else if (keywd == 1)                            /* handle COUNT */
  1077.         {
  1078.             anafile = NULL;                                    /* no output */
  1079.             done = TRUE;
  1080.         }
  1081.         else done = openoutfile (response);    /* see if we can output */
  1082.     }                                                                        /* end of loop 'til done */
  1083. }
  1084.  
  1085. short openoutfile (name)
  1086.     char *name;
  1087. {
  1088.     short keywd;
  1089.     char response [STRMAX];
  1090.     char *opentype;
  1091.  
  1092.     opentype = "w";                                            /* default open type */
  1093.     anafile = fopen (name, "r");
  1094.     if (anafile != NULL)                                /* got it? */
  1095.     {
  1096.         fseek (anafile, 0L, 2);                        /* reset to the end */
  1097.         if (ftell (anafile) != 0L)                /* position != 0?  (ie, not empty?) */
  1098.         {
  1099.             printf ("'%s' isn't empty.  Want to OVERWRITE or ADD to it [press RETURN to ADD]? ", name);
  1100.             keywd = getline ("", "#overwrite#add", 1, "add",
  1101.                                             "Please type OVERWRITE or ADD? ", overadd, response);
  1102.             if (keywd == 0)
  1103.                 opentype = "w";                                /* overwrite */
  1104.             else opentype = "a";                        /* add */
  1105.         }
  1106.         fclose (anafile);
  1107.     }
  1108.  
  1109.     anafile = fopen (name, opentype);        /* try to open it as desired */
  1110.  
  1111.     if (anafile == NULL)                                /* blew it? */
  1112.     {
  1113.         printf ("Sorry -- can't write to '%s'.  Try again?\n", name);
  1114.         return (0);
  1115.     }
  1116.     return (1);                                                    /* success */
  1117. }
  1118.  
  1119. short getline (    char *prompt,
  1120.             char *keywords, 
  1121.             short keyneeded,
  1122.             char *dft, 
  1123.             char *reprompt,
  1124.             short helpstate, 
  1125.             char *response)
  1126.                                                 /* INPUT: prompt */
  1127.                                             /* INPUT: keywords, like "#a#b#c" */
  1128.                                         /* INPUT: insist on a keyword? */
  1129.                                                     /* INPUT: default response */
  1130.                                             /* INPUT: repeated prompt */
  1131.                                         /* INPUT: help state */
  1132.                                             /* OUTPUT: response buffer */
  1133. {
  1134.     short done = 0;                                            /* flag to exit loop */
  1135.     short keyindex;                                            /* index of word in #string */
  1136.  
  1137.     printf ("%s", prompt);                            /* prompt 'em */
  1138.     while (! done)
  1139.     {
  1140.         gets (response);                                    /* get a line of input */
  1141.         if (strlen (response) == 0)                /* pressed RETURN? */
  1142.             strcpy (response, dft);                    /* yes: supply default */
  1143.  
  1144.         keyindex = keyfind ("#quit#help", response); /* see if it's a standard one */
  1145.         if (keyindex >= 0)                                /* found something? */
  1146.         {                                                                    /* handle QUIT or HELP */
  1147.             if (keyindex == 0)                            /* QUIT? */
  1148.             {
  1149.                 printf ("\n\n");
  1150.                 exit (0);
  1151.             }
  1152.             dohelp (helpstate);                            /* nope: HELP */
  1153.         }                                                                    /* end of standard keywords */
  1154.         else {                                                        /* not standard */
  1155.             keyindex = keyfind (keywords, response); /* look it up */
  1156.  
  1157.             if ( (keyindex >= 0)                        /* found something... */
  1158.                 || (! keyneeded) )                        /* ...or didn't need it */
  1159.                     done = TRUE;                                /* then we're satisfied */
  1160.         }                                                                    /* end of parsing response */
  1161.  
  1162.         if (! done) printf ("%s", reprompt);    /* about to loop? be pushy */
  1163.     }                                                                        /* end of loop 'til done */
  1164.  
  1165.     return (keyindex);                                    /* return keyword number or -1 */
  1166. }                                                                            /* end of getline() */
  1167.  
  1168. void dohelp (short state)
  1169.     
  1170. {
  1171.     printf ("\n");
  1172.     if (state == anahelp)
  1173.     {
  1174.         printf ("  Enter a word, name or phrase.  This program will print out all\n");
  1175.         printf ("  the combinations of words which can be made by rearranging the\n");
  1176.         printf ("  letters in the phrase you type in.  Very short phrases won't\n");
  1177.         printf ("  have many good anagrams, while long phrases may produce too\n");
  1178.         printf ("  many to sift through.\n");
  1179.     }
  1180.     else if (state == scf)
  1181.     {
  1182.         printf ("  You can print anagrams on the screen, store them in a file,\n");
  1183.         printf ("  or just count them without printing them anywhere.  To print\n");
  1184.         printf ("  them on the screen, type SCREEN or just press RETURN.  To count\n");
  1185.         printf ("  them, type COUNT.  To send them to a file, type the file's name.\n");
  1186.     }
  1187.     else if (state == overadd)
  1188.     {
  1189.         printf ("  You can replace the current contents of that document with the\n");
  1190.         printf ("  anagrams, or you can add them after the old contents.  To replace,\N");
  1191.         printf ("  type OVERWRITE.  To add, type ADD.\n");
  1192.     }
  1193.     else if (state == quithelp)
  1194.     {
  1195.         printf ("  When you press the space bar, it suspends anagram finding\n");
  1196.         printf ("  in case you want to quit.  To leave the program, type QUIT.\n");
  1197.         printf ("  To do another anagram, type STOP.  To resume, type anything else.\n");
  1198.     }
  1199.     else if (state == dict1)
  1200.     {
  1201.         printf ("  Enter the name of a dictionary file you'd like to use.  Usually,\n");
  1202.         printf ("  '%s' is used, but it doesn't seem to be available.\n", DFTFILE);
  1203.         printf ("  Any text-only file containing one word per line will do.\n");
  1204.     }
  1205.     else if (state == dict1dft)
  1206.     {
  1207.         printf ("  Enter the name of a dictionary file you'd like to use.  Press\n");
  1208.         printf ("  RETURN to use '%s', the default file.\n", DFTFILE);
  1209.     }
  1210.     else if (state == dict2)
  1211.     {
  1212.         printf ("  Enter the name of another dictionary file, or press RETURN\n");
  1213.         printf ("  if you don't want to enter any more.\n");
  1214.     }
  1215.     else if (state == helppage)
  1216.     {
  1217.         printf ("  Normally output to the screen rushes by unless you press the\n");
  1218.         printf ("  mouse button to freeze it or hit the space bar to suspend it.\n");
  1219.         printf ("  If you ask for 'paged' output, it'll stop after each screenful.\n");
  1220.     }
  1221.     else if (state == helppaused)
  1222.     {
  1223.         printf ("  Press RETURN to resume reading anagrams, STOP to do a different\n");
  1224.         printf ("  anagram, or QUIT to stop.\n");
  1225.     }
  1226.     else printf ("Sorry -- no help available here.\n");
  1227.  
  1228.     if (state != quithelp)
  1229.         printf ("  At any time, you can leave by typing QUIT.\n");
  1230.     printf ("\n");
  1231. }
  1232.  
  1233. short keyfind (words, oneword)
  1234.     char *words;
  1235.     char *oneword;
  1236. {
  1237.     short cindex;
  1238.     char wordcopy [STRMAX], lookupword [STRMAX];
  1239.     short wordnum;
  1240.  
  1241.     strcpy (wordcopy, oneword);
  1242.     clean (wordcopy);
  1243.     if (strlen (wordcopy) < 1) return (-1);    /* can't find nothing */
  1244.     strcpy (lookupword, "#");
  1245.     strcat (lookupword, wordcopy);            /* construct "#word" */
  1246.  
  1247.     cindex = findstr (words, lookupword);    /* look up "#word" in "#a#b... */
  1248.     if (cindex == -1)                                        /* not found? */
  1249.         return (-1);                                            /* say so */
  1250.  
  1251.     wordnum = 0;                                                /* initially we're at word zero */
  1252.     while (cindex-- > 0)                                /* loop up to "#" in "#word" in str */
  1253.         if (*words++ == '#')                            /* is there a "#"? */
  1254.             ++wordnum;                                            /* yes: that's another word */
  1255.  
  1256.     return (wordnum);
  1257. }
  1258.  
  1259. short findstr (master, sub)
  1260.     char *master;
  1261.     char *sub;
  1262. {
  1263.     short result = 0;
  1264.     short subsize = strlen (sub);
  1265.  
  1266.     while (*master)
  1267.     {
  1268.         if (strNequal (master, sub, subsize) == 1)    /* match? */
  1269.             return (result);                                /* yup: say where */
  1270.         ++result;
  1271.         ++master;
  1272.     }
  1273.  
  1274.     return (-1);                                                /* no match */
  1275. }
  1276.  
  1277. short strNequal (register char *s1,register char  *s2, register short size)
  1278. {    while (size--)
  1279.         if (*s1++ != *s2++) return 0;            /* not equal */
  1280.     return 1;                                                        /* equal */
  1281. }
  1282.  
  1283. long msec ()
  1284. {
  1285.     return (TickCount () * (1000/60));    /* convert from 1/60s to ms */
  1286. }
  1287.  
  1288. void starttimer ()
  1289. {
  1290.     startt = msec ();
  1291. }
  1292.  
  1293. void stoptimer ()
  1294. {
  1295.     endt = msec ();
  1296.     tottime += (endt-startt);
  1297. }
  1298.  
  1299. void inittimer ()
  1300. {
  1301.     tottime = 0;
  1302.     starttimer ();
  1303. }
  1304.  
  1305. void printtime ()
  1306. {
  1307.     stoptimer ();
  1308.     printf ("Computing time: %ld.%03ld seconds.  ",
  1309.                                     tottime/1000L, (tottime % 1000));
  1310. }
  1311.  
  1312. void chkerr (short i)
  1313. {
  1314.     if (i == EOF)
  1315.     {
  1316.         printf ("Sorry!  Error in writing to output file.  Perhaps your disk is full?\n");
  1317.         exit (0);
  1318.     }
  1319. }
  1320.